package com.amiba.crm.admin.service.impl;

import com.amiba.crm.admin.domain.entity.SysRegion;
import com.amiba.crm.admin.mapper.SysRegionMapper;
import com.amiba.crm.admin.service.SysRegionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("sysRegionService")
@AllArgsConstructor
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements SysRegionService {
	private SysRegionMapper sysRegionMapper;

	private static final List<SysRegion> regionListMap = new ArrayList<>();


    @Override
    public List<SysRegion> queryListExpand(){
        if(regionListMap.size()>0){
            return regionListMap;
        }
        LambdaQueryWrapper<SysRegion> wrapper = Wrappers.<SysRegion>query().lambda();
        wrapper.eq(SysRegion::getParentid,0);
        List<SysRegion> regionList = queryListParentId(wrapper);
        getMenuTreeList(regionList,0);
        regionListMap.addAll(regionList);
        return regionList;
    }


    public List<SysRegion> queryListParentId(LambdaQueryWrapper<SysRegion> wrapper) {
        wrapper.orderByAsc(SysRegion::getId);
        List<SysRegion> regionList = sysRegionMapper.selectList(wrapper);
        return regionList;
    }

    /**
     * 递归
     */
    private List<SysRegion> getMenuTreeList(List<SysRegion> regionList,Integer pid){
        List<SysRegion> subRegionList = new ArrayList<SysRegion>();
        if(regionList.size()==0){
            return subRegionList;
        }
        for(SysRegion entity : regionList){
            if(entity.getLevel() != 3){
                LambdaQueryWrapper<SysRegion> wrapper = Wrappers.<SysRegion>query().lambda();
                wrapper.eq(SysRegion::getParentid,entity.getCode());

                entity.setList(getMenuTreeList(queryListParentId(wrapper),entity.getId()));
            }
            subRegionList.add(entity);
        }

        return subRegionList;
    }
}
